package com.xindaoapp.happypet.activity;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Tuan;
import com.xindaoapp.happypet.view.TuanCustomDigitalClock;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class TuanActivity extends BaseLoadAnimationAcitivity implements OnClickListener {
    @ViewInject(R.id.tittle_shop_cancel)
    private ImageView tittle_shop_cancel;
    @ViewInject(R.id.tittle_shop_content)
    private TextView tittle_shop_content;

    @ViewInject(R.id.tuan_list)
    private PullToRefreshListView tuan_list;

    @ViewInject(R.id.no_result)
    private RelativeLayout no_result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_tuan);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initClick();
        initListView();
        initTuanData(page);
    }

    private void initListView() {
        if (tuan.size() > 4)
            tuan_list.setPullLoadEnabled(true);
        else
            tuan_list.setPullLoadEnabled(false);
        tuan_list.setPullRefreshEnabled(true);
        tuan_list.setScrollLoadEnabled(true);
        // 下拉刷新上拉加载
        tuan_list.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                tuan.clear();
                page = 1;
                initTuanData(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                initTuanData(++page);
            }
        });
        tuan_list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    Intent intent = new Intent(TuanActivity.this, ProductDetailActivity1.class);
                    intent.putExtra("productId", (tuan.get(position).goods_id));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private int page = 1;
    private TuanAdapter secAdapter;
    private static List<com.xindaoapp.happypet.bean.Tuan.Data.SecKillGood> tuan =
            new ArrayList<com.xindaoapp.happypet.bean.Tuan.Data.SecKillGood>();
    private boolean isFirst = true;

    private void initTuanData(final int i) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page));
        params.put("pageSize", Address.PAGECOMMONSIZE);
        // final ProgressHUD progressHUD =
        // ProgressHUD.show(TuanActivity.this, "正在加载...", true, true, null);
        AddClient.get(Address.TUAN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                /*
                 * if (null != progressHUD && progressHUD.isShowing()) { progressHUD.dismiss(); }
                 */
                try {
                    isFirst = false;
                    onDataArrived(true);
                    Tuan parse = JSON.parseObject(content, Tuan.class);

                    if (parse.getStatus().equals("1") && parse.data.info != null) {
                        List<com.xindaoapp.happypet.bean.Tuan.Data.SecKillGood> starting =
                                parse.data.info;
                        tuan.addAll(starting);
                        if (secAdapter == null) {
                            secAdapter = new TuanAdapter(tuan);
                            tuan_list.getRefreshableView().setAdapter(secAdapter);
                        } else {
                            secAdapter.notifyDataSetChanged();
                        }
                        if (Integer.parseInt(parse.data.count) < 15) {
                            tuan_list.setPullRefreshEnabled(false);
                            tuan_list.setScrollLoadEnabled(false);
                        }
                    } else {
                        Toast.makeText(TuanActivity.this, "没有更多数据", Toast.LENGTH_SHORT).show();
                    }
                    if (parse.getStatus().equals("1")) {
                        tuan_list.setVisibility(View.VISIBLE);
                        no_result.setVisibility(View.GONE);
                        if (parse.data.info.size() == 0 && tuan.size() == 0) {
                            no_result.setVisibility(View.VISIBLE);
                            tuan_list.setVisibility(View.GONE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    no_result.setVisibility(View.VISIBLE);
                    tuan_list.setVisibility(View.GONE);
                }
                onLoaded();
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                onLoaded();
                if (isFirst) {
                    onDataArrived(false);
                    SetOnLoadFailListener(new OnLoadFailListener() {
                        @Override
                        public void onLoadFail() {
                            initTuanData(1);
                        }
                    });
                } else {
                    onDataArrived(true);
                }
                super.onFailure(error, content);
            }
        });
    }

    private void onLoaded() {
        tuan_list.onPullDownRefreshComplete();
        tuan_list.onPullUpRefreshComplete();
    }

    private class TuanAdapter extends BaseAdapter {
        private final List<com.xindaoapp.happypet.bean.Tuan.Data.SecKillGood> tuan1;

        public TuanAdapter(List<com.xindaoapp.happypet.bean.Tuan.Data.SecKillGood> tuan1) {
            super();
            this.tuan1 = tuan1;
        }

        @Override
        public int getCount() {
            return tuan1.size();
        }

        @Override
        public Object getItem(int position) {
            return tuan1.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(TuanActivity.this, R.layout.good_tuan_item, null);
                holder.good_pic = (ImageView) convertView.findViewById(R.id.good_pic);
                holder.good_name = (TextView) convertView.findViewById(R.id.good_name);
                holder.good_shop_price = (TextView) convertView.findViewById(R.id.good_shop_price);
                holder.good_market_price =
                        (TextView) convertView.findViewById(R.id.good_market_price);
                holder.good_sell = (TextView) convertView.findViewById(R.id.good_sell);
                holder.good_surplus = (TextView) convertView.findViewById(R.id.good_surplus);
                holder.tuan_time =
                        (TuanCustomDigitalClock) convertView.findViewById(R.id.tuan_time);
                holder.tuancount = (TextView) convertView.findViewById(R.id.tuancount);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.good_name.setText(tuan1.get(position).goods_name);
            holder.good_shop_price
                    .setText(formatPrice(Float.valueOf(tuan1.get(position).ext_infos.price_ladder
                            .get(0).price)));
            holder.good_market_price.setText("￥"
                    + formatPrice(Float.valueOf(tuan1.get(position).market_price)));
            holder.good_market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.good_sell.setText(formatDaZhe(Float.parseFloat(formatDaZhe(Float.valueOf(tuan1
                    .get(position).ext_infos.price_ladder.get(0).price)
                    * 10
                    / Float.valueOf(tuan1.get(position).market_price)))) + "折");
            holder.good_surplus.setText(tuan1.get(position).goods_number);

            holder.tuancount.setText(tuan1.get(position).sold_number + "人已团购");
            holder.tuan_time.setEndTime((formatDate(tuan1.get(position).end_time)));

            ImageLoader.getInstance()
                    .displayImage(tuan1.get(position).goods_thumb, holder.good_pic);
            return convertView;
        }
    }

    private String formatDaZhe(Float a) {
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(a);
    }

    private String formatPrice(Float a) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(a);
    }

    class ViewHolder {
        ImageView good_pic;
        TextView good_name;
        TextView good_shop_price;
        TextView good_market_price;
        TextView good_sell;
        TextView good_surplus;
        TextView tuancount;
        TuanCustomDigitalClock tuan_time;
    }

    public static long formatDate(String data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(data).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void initClick() {
        tittle_shop_cancel.setOnClickListener(this);
        tittle_shop_content.setText("尾巴圈团");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_shop_cancel:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (tuan.size() > 0) {
            tuan.clear();
        }
        super.onDestroy();
    }
}
